//
//  JJJMainViewController.swift
//  myBlog
//
//  Created by 姜军君 on 15/11/25.
//  Copyright © 2015年 JJJ. All rights reserved.
//

import UIKit

class JJJMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加所有子控制器
        addChildViewControllers()
     }
    
    override func viewDidAppear(animated: Bool) {
        
        // 添加加号按钮
        setupComposeBtn()
    }
    
    /// 添加所有子控制器
    private func addChildViewControllers() {
        
        addChildViewController(JJJHomeViewController(), title: "主页", imageName: "tabbar_home")
        addChildViewController(JJJMessageViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(JJJDiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(JJJProfileViewController(), title: "我的", imageName: "tabbar_profile")
    }
    
    /// 添加子控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String){
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
 
        // 和上面是完全相等的
//        nav.tabBarItem.image = UIImage(named: "tabbar_home")
        
//        tabBar.tintColor =  UIColor.orangeColor()

        addChildViewController(nav)
    }
    
    /// 添加加号按钮
    private func setupComposeBtn() {
        
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
    }
    
    /// 加号按钮点击事件
    func composeBtnDidClicked() {
        
        print("不要点我!!!")
    }
    
    /// 懒加载
    lazy private var composeButton: UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        btn.addTarget(self, action: "composeBtnDidClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.tabBar.addSubview(btn)
        
        return btn
        }()
}
